package com.zito.utils;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang.ArrayUtils;

import com.downlove.database.DBException;
import com.downlove.database.QueryHelper;

/**
 * OSChina底层数据库操作的类
 * 
 * @see QueryHelper
 */
public class QueryHelperExtend extends QueryHelper{

	private final static QueryRunner _g_runner = new QueryRunner();


	/**
	 * 查询出结果集，并封装成List<Map>对象
	 * 
	 * @param sql
	 *            sql语句
	 * @param params
	 *            参数数组
	 * @return 封装为List<Map>的对象
	 */
	public static List<Map<String, Object>> queryListMap(String sql,
			Object... params) {
		try {
			return (List<Map<String, Object>>) _g_runner.query(getConnection(),
					sql, new MapListHandler(), params);
		} catch (SQLException e) {
			throw new DBException(e);
		}
	}

	/**
	 * 查询出结果集，并封装成List<Map>对象
	 * 
	 * @param sql
	 *            sql语句
	 * @param params
	 *            参数数组
	 * @return 封装为List<Map>的对象
	 */
	public static List<Map<String, Object>> queryListMapPage(String sql, int page,
			int count, Object... params) {
		if (page < 0 || count < 0)
			throw new IllegalArgumentException(
					"Illegal parameter of 'page' or 'count', Must be positive.");
		count = (count > 0) ? count : Integer.MAX_VALUE;
		try {
			int from = page > 0 ? (page - 1) * count : 0;
			return (List<Map<String, Object>>) _g_runner.query(getConnection(),
					sql + " LIMIT ?,?", new MapListHandler(),
					ArrayUtils.addAll(params, new Integer[] { from, count }));
		} catch (SQLException e) {
			throw new DBException(e);
		}
	}
}
